#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import threading
from com.zxy.z_debug import z_debug
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.zxy.business.Ope_DB_Cent import Ope_DB_Cent
from com.zxy.common import Com_Para
from com.zxy.common.Cal_Auto_Run import Cal_Auto_Run
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.common.DbConfigSelf import DbConfigSelf
from com.zxy.comport.ComDev import ComDev
from com.zxy.taskhandler.TimeLoopTask import TimeLoopTask
from com.zxy.taskhandler.TimeTask import TimeTask
from com.zxy.tcp.ClientThread import ClientThread
from com.zxy.tcp.ServerThread import  ServerThread
from com.zxy.tcp.ServerThreadHttp import ServerThreadHttp
from com.zxy.tcp.MqttThread import MqttThread
from com.zxy.autoUpdate.GetVersion import GetVersion
import sys
class Init_Page(z_debug):
    def __init__(self):
        pass
    @staticmethod
    def Start_Http():
        if Com_Para.bThread == True:
            temSthttp = ServerThreadHttp("", "", Com_Para.port)
            t1 = threading.Thread(target=temSthttp.run, name="ServerHttpThread")
            t1.start()
    @staticmethod
    def NormalRun():
        bFlag = True      
        if Com_Fun.flagSconnections() == False:
            Com_Para.S_DESC = "超过系统试用版本时间"
            bFlag = False        
        if bFlag == False:            
            arySession = Com_Para.strSessionAva.split(";")
            for temSession in arySession:
                if temSession != Com_Fun.MacAddrTrue(Com_Fun.GetMacAddr()):
                    Com_Para.S_DESC = Com_Para.S_DESC + "或运行key错误，请联系技术人员" + Com_Fun.GetMacAddr()
                    uL = UsAdmin_Log(Com_Para.ApplicationPath, Com_Para.S_DESC)
                    uL.WriteLog()
                    bFlag = False
                else:
                    bFlag = True
                    break
        else:
            bFlag = True
        return True   
    @staticmethod
    def Start_Server():        
        if Init_Page.NormalRun() == False :
            return False        
        if Com_Para.If_Parent_Device == 1:
            st = ServerThread("", "", Com_Para.AccSocketPort)
            t2 = threading.Thread(target=st.run, name="ServerMainThread")
            t2.start()
    @staticmethod
    def Start_Client():
        if Init_Page.NormalRun() == False :
            return False
        if Com_Para.If_Child_Device == 1:
            if Com_Para.ServerIP != "" and Com_Para.ServerPort != "":
                ct = ClientThread(60, Com_Para.ServerIP, int(Com_Para.ServerPort))
                t3 = threading.Thread(target=ct.run, name="ClientMainThread")
                t3.start()        
            try: 
                for temSIP in Com_Para.ServerIPList.split(";"):
                    if temSIP != "":
                        sttem = ClientThread(10, temSIP.split(":")[0], int(temSIP.split(":")[1]))
                        t4tem = threading.Thread(target=sttem.list_run, name="ClientMainThread" + temSIP.split(":")[0])
                        t4tem.start()
            except Exception as e:
                print("TCP client error:" + repr(e))
            finally:
                pass
    @staticmethod
    def Start_ComPort():
        if Init_Page.NormalRun() == False :
            print(Com_Para.S_DESC)
            return False
        iIndex = 0   
        for temComPort in Com_Para.ComPortList.split(";"):
            iIndex = iIndex + 1
            temComPortInfo = temComPort.split(",")   
            try: 
                if len(temComPortInfo) == 5 and Com_Fun.GetHashTableNone(Com_Para.htComPort, temComPortInfo[4]) is None:
                    temCD = ComDev(temComPortInfo[0], int(temComPortInfo[1]), int(temComPortInfo[2]), int(temComPortInfo[3]), iIndex)
                    temCD.attPortName = temComPortInfo[4]
                    Com_Fun.SetHashTable(Com_Para.htComPort, temComPortInfo[4], temCD)
            except Exception as e:
                print("com link error:"+temComPortInfo[0]+"==>"  + repr(e))
            finally:
                pass
    @staticmethod
    def Start_TimeTask(inputInterval):        
        if Init_Page.NormalRun() == False :
            print(Com_Para.S_DESC)
            return False
        if Com_Para.urlPath != "":
            gv = GetVersion()
            gv.CheckVersion()
        tt = TimeTask(0, 0, inputInterval, 0.1, "TimeTask")
        tt.run()
    @staticmethod
    def Start_MQTT():        
        if Init_Page.NormalRun() == False :
            return False
        if Com_Para.MQTT_host != "":            
            ct = MqttThread()
            t3 = threading.Thread(target=ct.run, name="ClientMqttThread")
            t3.start()
    @staticmethod
    def Start_TimeLoop():        
        if Init_Page.NormalRun() == False :
            return False
        iIndex = 0
        for num in Com_Para.CustTimeTaskNum.split(";"):
            iLoop = 86400
            try: 
                iLoop = int(num)
            except Exception as e:
                pass
            finally:
                pass
            temREFLECT_IN_CLASS = ""
            if len(Com_Para.CustTimeREFLECT_IN_CLASS.split(";")) > iIndex:
                temREFLECT_IN_CLASS = Com_Para.CustTimeREFLECT_IN_CLASS.split(";")[iIndex]
                tt = TimeLoopTask(iLoop, 0.1, temREFLECT_IN_CLASS)
                tt.run()
            iIndex = iIndex + 1
    @staticmethod
    def Init_Load():
        DbConfigSelf.GetDbConfigSelfNew()
        temOpd = Ope_DB_Cent()
        temListT_DB_CONFIG = temOpd.Get_T_DB_CONFIG()
        for temItem in temListT_DB_CONFIG:
            Com_Fun.SetHashTable(Com_Para.htDb, temItem.attMAIN_ID, temItem)
            try:
                if temItem.attMAIN_ID == 1:
                    pass
                elif temItem.attMAIN_ID == 2:
                    pass
                elif temItem.attMAIN_ID == 3:
                    pass
                elif temItem.attMAIN_ID == 4:
                    pass
                elif temItem.attMAIN_ID == 5:
                    pass
                elif temItem.attMAIN_ID == 6:
                    pass
                elif temItem.attMAIN_ID == 7:
                    pass
                elif temItem.attMAIN_ID == 8:
                    pass
                elif temItem.attMAIN_ID == 9:
                    pass
                else:
                    pass                    
            except Exception as e:
                print("Init_Load:" + repr(e))
        temOpd.Init_Load()
        Cal_Auto_Run.init_data()